const cors = require('cors');

/**
 * CORS 中间件配置
 */
const corsOptions = {
  origin: function (origin, callback) {
    // 开发环境允许所有来源
    if (process.env.NODE_ENV === 'development') {
      return callback(null, true);
    }

    // 生产环境严格控制来源
    const allowedOrigins = [
      process.env.CLIENT_URL,
      process.env.ADMIN_URL,
      process.env.FRONTEND_URL,
      'http://localhost:8080',
      'http://localhost:3000',
      'http://localhost:5173', // Vite 默认端口
      'http://localhost:8000',
      'http://127.0.0.1:8080',
      'http://127.0.0.1:3000',
      'http://127.0.0.1:5173',
      'https://servicewechat.com' // 微信小程序域名
    ].filter(Boolean); // 过滤掉 undefined 值
    
    // 允许无origin的请求（如移动端APP、Postman等）
    if (!origin) return callback(null, true);
    
    if (allowedOrigins.includes(origin)) {
      callback(null, true);
    } else {
      console.warn(`CORS blocked: ${origin} not in allowed origins`);
      console.warn(`Allowed origins:`, allowedOrigins);
      callback(new Error('不允许的CORS来源'));
    }
  },
  credentials: true, // 允许携带cookie
  methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS', 'PATCH'],
  allowedHeaders: [
    'Content-Type', 
    'Authorization', 
    'X-Requested-With', 
    'Accept',
    'Origin',
    'Cache-Control',
    'X-File-Name',
    'Access-Control-Allow-Origin'
  ],
  exposedHeaders: ['X-Total-Count', 'X-Page-Count'], // 暴露给前端的响应头
  maxAge: 86400, // 预检请求缓存时间（24小时）
  preflightContinue: false,
  optionsSuccessStatus: 200 // 某些旧版浏览器对204状态码有问题
};

/**
 * 创建 CORS 中间件
 */
function createCorsMiddleware() {
  if (process.env.ENABLE_CORS === 'false') {
    console.log('CORS已禁用');
    return (req, res, next) => next();
  }
  
  console.log('CORS已启用');
  return cors(corsOptions);
}

/**
 * 处理预检请求的中间件
 */
function handlePreflight(req, res, next) {
  if (req.method === 'OPTIONS') {
    res.header('Access-Control-Allow-Origin', req.headers.origin || '*');
    res.header('Access-Control-Allow-Methods', 'GET,POST,PUT,DELETE,OPTIONS,PATCH');
    res.header('Access-Control-Allow-Headers', 'Content-Type,Authorization,X-Requested-With,Accept,Origin,Cache-Control,X-File-Name');
    res.header('Access-Control-Allow-Credentials', 'true');
    res.header('Access-Control-Max-Age', '86400');
    return res.status(200).end();
  }
  next();
}

module.exports = {
  corsOptions,
  createCorsMiddleware,
  handlePreflight
}; 